package net.arvin.mobilebanksystem.fragment;

import java.util.Calendar;

import net.arvin.dao.ResponseHandler;
import net.arvin.mobilebanksystem.R;
import net.arvin.mobilebanksystem.activity.UserInfoActivity;
import net.arvin.model.User;
import net.arvin.service.UserService;
import net.arvin.utils.NetConnectionUtil;
import net.arvin.view.NormalDialog.MyDialogListener;
import net.arvin.view.SexSelectorDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

public class RegisterFragment extends Fragment implements OnClickListener {
	private EditText phonenumber_et;
	private EditText nickname_et;
	private EditText password_et;
	private EditText answer_et;
	private EditText email_et;
	private TextView sex_et;
	private TextView birthdaySelector;
	private TextView delegate;
	private Button registerBtn;
	private SexSelectorDialog mDialog;
	private boolean isSelect = false;
	private ResponseHandler mResponseHandler;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_register, null);
		init(view);
		return view;
	}

	private void init(View view) {
		initView(view);
		initLisetner();
	}

	private void initLisetner() {
		sex_et.setOnClickListener(this);
		birthdaySelector.setOnClickListener(this);
		delegate.setOnClickListener(this);
		registerBtn.setOnClickListener(this);
	}

	private void initView(View view) {
		phonenumber_et = (EditText) view.findViewById(R.id.phonenumber_et);
		nickname_et = (EditText) view.findViewById(R.id.nickname_et);
		password_et = (EditText) view.findViewById(R.id.password_et);
		answer_et = (EditText) view.findViewById(R.id.answer_et);
		email_et = (EditText) view.findViewById(R.id.email_et);
		sex_et = (TextView) view.findViewById(R.id.sex_et);
		birthdaySelector = (TextView) view.findViewById(R.id.birthday_selector);
		delegate = (TextView) view.findViewById(R.id.text_delegate);
		registerBtn = (Button) view.findViewById(R.id.register);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.sex_et:
			selectSex();
			break;
		case R.id.birthday_selector:
			selectorDate();
			break;
		case R.id.text_delegate:
			Toast.makeText(getActivity(), "text_delegate clicked",
					Toast.LENGTH_SHORT).show();
			break;
		case R.id.register:
			registerValidate();
			break;
		}
	}

	private void selectorDate() {
		final DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(final DatePicker datePicker, final int year,
					final int month, final int dayOfMonth) {
				birthdaySelector.setText(year + "-" + (month + 1) + "-"
						+ dayOfMonth);
				isSelect = true;
			}
		};
		int year = Calendar.getInstance().get(Calendar.YEAR);
		int month = Calendar.getInstance().get(Calendar.MONTH);
		int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
		String birthday = birthdaySelector.getText().toString();
		if (isSelect) {
			int f = birthday.indexOf("-");
			int e = birthday.lastIndexOf("-");
			year = Integer.parseInt(birthday.substring(0, f));
			month = Integer.parseInt(birthday.substring(f + 1, e)) - 1;
			day = Integer
					.parseInt(birthday.substring(e + 1, birthday.length()));
		}
		final Dialog dialog = new DatePickerDialog(getActivity(), dateListener,
				year, month, day);
		dialog.setTitle("设置生日");
		dialog.show();
	}

	private void selectSex() {
		mDialog = new SexSelectorDialog(getActivity(), R.style.MyDialog,
				new MyDialogListener() {

					@Override
					public void onClick(View view) {
						switch (view.getId()) {
						case R.id.dialog_btn_male:
							sex_et.setText("男");
							mDialog.dismiss();
							break;
						case R.id.dialog_btn_female:
							sex_et.setText("女");
							mDialog.dismiss();
							break;
						case R.id.dialog_btn_cancel:
							mDialog.dismiss();
							break;
						}
					}
				});
		mDialog.show();
	}

	private void registerValidate() {
		if (phoneNumberCheck() && nicknameChecked() && passwordChecked()&&answerChecked()
				&& emailChecked() && sexChecked() && birthdayChecked()) {
			if (NetConnectionUtil.isConnectWithTip(getActivity(), "没有联网=_=!")) {
				UserService.tryRegister(getUserJSON(), getResponseHandler(),
						getActivity());
			}
		}
	}

	private String getUserJSON() {
		User userBean = new User();
		userBean.setPhonenumber(phonenumber_et.getText().toString());
		userBean.setNickname(nickname_et.getText().toString());
		userBean.setPassword(password_et.getText().toString());
		userBean.setQuestion("您的出生地？");
		userBean.setAnswer(answer_et.getText().toString());
		userBean.setEmail(email_et.getText().toString());
		userBean.setSex(sex_et.getText().toString());
		userBean.setBirthday(birthdaySelector.getText().toString());
		userBean.setAcountbalance(0f);
		System.out.println(JSON.toJSONString(userBean));
		return JSON.toJSONString(userBean);
	}

	private ResponseHandler getResponseHandler() {
		if (mResponseHandler == null) {
			mResponseHandler = new ResponseHandler() {
				@Override
				public void onRequsetSucceeded(final Object data) {
					// User user = JSON.parseObject(data.toString(),
					// User.class);
					Toast.makeText(getActivity(), "注册成功!", Toast.LENGTH_SHORT)
							.show();
					startLoginActivity();
				}

				@Override
				public void onRequestFailed(final Object data) {
					Toast.makeText(getActivity(), "该手机号已被使用!",
							Toast.LENGTH_SHORT).show();
				}
			};
		}
		return mResponseHandler;
	}

	private void startLoginActivity() {
		Intent tent = new Intent(getActivity(), UserInfoActivity.class);
		startActivity(tent);
		getActivity().finish();
	}

	private boolean birthdayChecked() {
		String birthday = birthdaySelector.getText().toString();
		if (birthday == null || birthday.trim().equals("")) {
			Toast.makeText(getActivity(), "生日不能为空", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	private boolean sexChecked() {
		String sex = sex_et.getText().toString();
		if (sex == null || sex.trim().equals("")) {
			Toast.makeText(getActivity(), "性别不能为空", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	private boolean emailChecked() {
		String email = email_et.getText().toString();
		if (email == null || email.trim().equals("")) {
			Toast.makeText(getActivity(), "邮箱不能为空!!", Toast.LENGTH_SHORT)
					.show();
			return false;
		} else {
			if (!email.matches("\\w+@\\w+(\\.\\w+)+")) {
				Toast.makeText(getActivity(), "邮箱格式不正确!!", Toast.LENGTH_SHORT)
						.show();
				return false;
			}
		}
		return true;
	}

	private boolean answerChecked(){
		String answer = answer_et.getText().toString().trim();
		if(answer ==null || answer.equals("")){
			Toast.makeText(getActivity(), "密保答案不能为空~", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}
	
	private boolean passwordChecked() {
		String password = password_et.getText().toString();
		if (password == null || password.trim().equals("")) {
			Toast.makeText(getActivity(), "密码不能为空~", Toast.LENGTH_SHORT).show();
			return false;
		} else {
			if (!password.matches("^[a-zA-Z0-9]\\w{3,15}$")) {
				Toast.makeText(getActivity(), "密码只能是4-16为之间的数字、字母组成~",
						Toast.LENGTH_SHORT).show();
				return false;
			}
		}
		return true;
	}

	private boolean nicknameChecked() {
		String nickName = nickname_et.getText().toString();
		if (nickName == null || nickName.trim().equals("")) {
			Toast.makeText(getActivity(), "昵称不能为空~", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	private boolean phoneNumberCheck() {
		String phonenumber = phonenumber_et.getText().toString();
		if (phonenumber == null || phonenumber.trim().equals("")) {
			Toast.makeText(getActivity(), "手机号不能为空~", Toast.LENGTH_SHORT)
					.show();
			return false;
		} else {
			if (phonenumber.trim().length() != 11) {
				Toast.makeText(getActivity(), "手机号长度不对~", Toast.LENGTH_SHORT)
						.show();
				return false;
			}
			return true;
		}
	}
}
